<template>
  <div v-if="item.children" class="menu-group">
    <div class="main-menu" :class="{open: openKeys.includes(item.key)}" @click="$emit('toggle-menu', item.key)">
      <div class="menu-item-content">
        <i :class="item.icon"></i>
        <span>{{ item.label }}</span>
      </div>
      <i class="menu-toggle fas fa-chevron-down" :class="{rotate: openKeys.includes(item.key)}"></i>
    </div>
    <div
      class="submenu"
      :class="{expanded: openKeys.includes(item.key)}"
      ref="submenuRef"
      :style="submenuStyle"
    >
      <SidebarMenuItem
        v-for="sub in item.children"
        :key="sub.key"
        :item="sub"
        :active-key="activeKey"
        :open-keys="openKeys"
        :parent-key="item.key"
        @toggle-menu="$emit('toggle-menu', $event)"
        @menu-click="$emit('menu-click', $event, item.key)"
      />
    </div>
  </div>
  <a v-else href="#" class="menu-item" :class="{active: activeKey === item.key}" @click.prevent="$emit('menu-click', item, parentKey)">
    <i :class="item.icon"></i>
    <span>{{ item.label }}</span>
  </a>
</template>

<script setup lang="ts">
import { ref, watch, computed, nextTick } from 'vue'
import SidebarMenuItem from './SidebarMenuItem.vue'
const props = defineProps<{ item: any; activeKey: string; openKeys: string[]; parentKey?: string }>()
const emit = defineEmits(['menu-click', 'toggle-menu'])
const submenuRef = ref<HTMLElement | null>(null)
const submenuStyle = ref({})

watch(() => props.openKeys.includes(props.item.key), async (expanded) => {
  await nextTick()
  if (submenuRef.value) {
    if (expanded) {
      const h = submenuRef.value.scrollHeight
      submenuStyle.value = {
        maxHeight: h + 'px',
        opacity: 1,
        transition: 'max-height 0.5s cubic-bezier(0.4,0,0.2,1), opacity 0.35s cubic-bezier(0.4,0,0.2,1)'
      }
    } else {
      submenuStyle.value = {
        maxHeight: '0px',
        opacity: 0,
        transition: 'max-height 0.5s cubic-bezier(0.4,0,0.2,1), opacity 0.35s cubic-bezier(0.4,0,0.2,1)'
      }
    }
  }
}, { immediate: true })
</script>

<script lang="ts">
export default {}
</script> 